Exchange

How to get current file name from selected file - Android Studio Tutorials

 on Button Click Event


uploadButton.setOnClickListener(v -> {
// Open a file picker to choose a PDF file
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select PDF"), PICK_PDF_REQUEST);
});

Then


// This code should be called when the user has selected a PDF file and the activity result is returned
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null) {
pdfUri = data.getData();
String fileName = getFileNameFromUri(this, pdfUri);

if (fileName != null) {
// Do something with the selected file name
//Log.d(TAG, "Selected PDF file name: " + fileName);
Toast.makeText(this, "Selected PDF file name: " + fileName, Toast.LENGTH_SHORT).show();
}
}
}

// This is the same method as the one I provided in my previous response
private String getFileNameFromUri(Context context, Uri uri) {
String fileName = null;
String[] projection = {MediaStore.Images.Media.DISPLAY_NAME};
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
fileName = cursor.getString(columnIndex);
cursor.close();
}
return fileName;
}

Android Studio Tutorials
Android Studio Tutorials



Post a Comment

0 Comments